package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.Const;
import jsyf.com.util.BaseUtils;
import jsyf.oa.dao.system.DepartDao;
import jsyf.oa.dao.system.RoleDao;
import jsyf.oa.dao.system.UserDao;
import jsyf.oa.entity.system.RoleEntity;
import jsyf.oa.facade.system.RoleFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class RoleService implements RoleFacade {

    @Autowired
    private RoleDao dao;
    @Autowired
    private UserDao userDao;


    @Override
    public String save(String jsonData) {
        RoleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RoleEntity.class);
        if (StringUtils.isEmpty(entity.getId()) || "0".equals(entity.getId())) {
            entity.setTargetNumber(0);
            dao.add(entity);
        } else {
            RoleEntity oldEntity = dao.getEntityById(entity.getId());
            oldEntity.setName(entity.getName());
            oldEntity.setDepartId(entity.getDepartId());
            oldEntity.setSortNo(entity.getSortNo());
            oldEntity.setDelFlag(entity.getDelFlag());
            oldEntity.setRoleNameId(entity.getRoleNameId());
            dao.update(oldEntity);
        }
        return entity.getId();
    }

    @Override
    public String saveTargetNumber(String jsonData) {
        RoleEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), RoleEntity.class);
        RoleEntity oldEntity = dao.getEntityById(entity.getId());
        if (entity.getTargetNumber() != null) {
            oldEntity.setTargetNumber(entity.getTargetNumber());
        }
        dao.update(oldEntity);
        return entity.getId();
    }

    @Override
    public String delById(String id) {
        Integer userCount = userDao.getPageCount(" AND ROLE_ID=? AND DEL_FLAG=0", new Object[]{id});
        if (userCount > 0) {
            return BaseUtils.errorrRespond("删除失败，请先删除人员");
        }
        int flag = this.dao.delById(id);
        if (Const.INT_ONE == flag) {
            return BaseUtils.succsessObjRespond("删除成功");
        }
        return BaseUtils.errorrRespond("删除失败");
    }

    @Override
    public List<JSONObject> getByUserId(String userId) {
        return dao.getJSONListByCondition(" AND USER_ID = ? ", new Object[]{userId});
    }

    @Override
    public Boolean sort(String roleIds) {
        return dao.sort(roleIds);
    }
}
